from django.core.cache import cache

from contents.models import ContentCategory
from goods.models import GoodsChannelGroup


def get_categories():
    data = cache.get('categories')
    if not data:
        data={}
        #获取所有频道组
        channels_group_all=GoodsChannelGroup.objects.all()
        #每个频道组
        for channel_group in channels_group_all:
            channel_group_data={
                'channels':[],
                'sub_cats':[]
            }
            data[channel_group.id]=channel_group_data
        #每个频道
            for channel in channel_group.goodschannel_set.all():
                #一级类
                cat1=channel.category
                channel_data={'id':channel.id,'name':cat1.name,'url':channel.url}
                channel_group_data['channels'].append(channel_data)
                for cat2 in cat1.subs.all():
                    cat2_data={
                        'id':cat2.id,'name':cat2.name,'sub_cats':[]
                    }
                    channel_group_data['sub_cats'].append(cat2_data)
                    for cat3 in cat2.subs.all():
                        cat3_data={
                            'id':cat3.id,'name':cat3.name
                        }
                        cat2_data['sub_cats'].append(cat3_data)

        cache.set('categories', data, 3600)
    return data

